package com.neu.service;

/*
待办清单服务类
新增和删除待办清单功能
 */

import com.neu.model.Item;
import com.sun.tools.javac.Main;
import jakarta.enterprise.context.ApplicationScoped;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class ItemService {

    //InputStream inputStream = Main.class.getResourceAsStream("/todo.csv");
    private final String fileName = "/todo.csv";
    private final String DELIMITER = ",";

    public List<Item> getAllTodos() {
        List<Item> todos = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split(DELIMITER);
                Item item = new Item();
                item.setId(Long.parseLong(data[0]));
                item.setItemName(data[1]);
                item.setState(Boolean.parseBoolean(data[2]));
                todos.add(item);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return todos;
    }

    public void saveAllTodos(List<Item> todos) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
            for (Item todo : todos) {
                bw.write(todo.getId() + DELIMITER +
                        todo.getItemName() + DELIMITER +
                        todo.getState() + DELIMITER);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 追加写
    public void saveTodo(Item todo) {
        try (FileWriter writer = new FileWriter(fileName, true);
             BufferedWriter bw = new BufferedWriter(writer);
             PrintWriter out = new PrintWriter(bw)) {
            out.println(todo.getId() + DELIMITER +
                    todo.getItemName() + DELIMITER +
                    todo.getState() + DELIMITER);
        } catch (IOException e) {
            System.err.println("追加内容到文件时出现异常：" + e.getMessage());
        }
    }

    public void deleteAll() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
            // 清空文件
            bw.write("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteTodo(long id){
        List<Item> todos = getAllTodos();
        for (Item todo : todos){
            if(todo.getId() == id){
                todos.remove(todo);
            }
        }
        deleteAll();
        saveAllTodos(todos);
    }

    public void changeState(Item item){
        List<Item> todos = getAllTodos();
        for (Item todo : todos){
            if(todo.getId() == item.getId()){
                todo.setState(item.getState());
            }
        }
        deleteAll();
        saveAllTodos(todos);
    }
}
